package zmee.bid.oa;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import zmee.entity.*;
import zmee.util.BosUtil;
import zmee.util.OARequestUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author lijiawang
* @Date 2022/11/24 17:27
* @Description:标书编制、招标公告提交至OA审批
*/
public class SrcBiddocOperPlugin extends AbstractOperationServicePlugIn {
    private Log log = LogFactory.getLog(SrcBiddocOperPlugin.class);

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        String key = e.getOperationKey();
        DynamicObject[] entities = e.getDataEntities();
        if (key.equals("submit")) {
            for (DynamicObject entitie : entities) {
                String formName = entitie.getDataEntityType().getName();
                DynamicObject dynamic = BusinessDataServiceHelper.loadSingle(entitie.getPkValue(), formName);
                DynamicObject org = dynamic.getDynamicObject("org");
                List<Map<String, Object>> attachmentpanel = AttachmentServiceHelper.getAttachments(formName, dynamic.getPkValue(), "attachmentpanel");
                // 2023-7-10 取消组织过滤判断
//                if (!org.getBoolean("zmee_oa")) {
                        List<Map<String, String>> list = new ArrayList<>();
                        for (int i = 0; i < attachmentpanel.size(); i++) {
                            Map<String, String> mapUrl = new HashMap<>();
                            Map<String, Object> map = attachmentpanel.get(i);
                            mapUrl.put("fieldName", "zbwj");
                            String names = map.get("name").toString();
                            String[] split = names.split("&");
                            StringBuffer name = new StringBuffer();
                            for (int j = 0; j < split.length; j++) {
                                if ((j + 1) == split.length) {
                                    name.append(split[0]);
                                } else {
                                    name.append(split[0] + "&amp;");
                                }
                            }
                            mapUrl.put("fieldType", "http:" + name);
                            String url = map.get("url").toString();
                            String substring = url.substring(0, url.indexOf("&") + 1);
                            mapUrl.put("fieldValue", substring + "amp;access_token=" + BosUtil.getLoginToken());
                            list.add(mapUrl);
                        }
                        log.info("biddoc");
                        biddoc(dynamic, list);
//                } else {
//                    List<Map<String, String>> fj = getEntrAttachmentlist(dynamic, "fj");
//                    publishnotice(dynamic,fj);
//                }
            }
        }
    }

    private void biddoc(DynamicObject dynamic, List<Map<String, String>> attacs) {
        //表头请求信息
        Map info = new HashMap();
        info.put("resource", "优采云");
        DynamicObject user = dynamic.getDynamicObject("aosqr");
        info.put("usderid", user.getString("username"));
        info.put("accountType", 1);
        info.put("name", "环能实业-招标文件审核流程");//请求标题
        info.put("workflowName", "环能实业-招标文件审核流程");//工作流标题
        info.put("workflowId", "274272");//工作流ID
        //info.put("isnextflow", 0);
        //表头字段
        Map<String, Object> mainfieldMap = OAutil.getMainfieldMap(dynamic);
        log.info("==mainfieldMap==" + mainfieldMap);
        //表头附件
        //项目启动单
        DynamicObject project = BusinessDataServiceHelper.loadSingle("src_project", "id", new QFilter[]{new QFilter("billno", QCP.equals, dynamic.getString("billno"))});
        DynamicObject single = BusinessDataServiceHelper.loadSingle(project.getPkValue(), "src_project");
        //招标立项申请单
        String source = single.get("source.number").toString();
        DynamicObject demand = BusinessDataServiceHelper.loadSingle(source, "src_demand");
        List<Map<String, Object>> attachmentpanels = AttachmentServiceHelper.getAttachments(demand.getDynamicObjectType().getName(), demand.getPkValue(), "attachmentpanel");

        List<Map<String, String>> mapUrl = OAutil.urlList(attachmentpanels, "fj");
        if (attacs != null && attacs.size() > 0) {
            for (int i = 0; i < attacs.size(); i++) {
                mapUrl.add(attacs.get(i));
            }
        }

        String type = single.getString("biztype.number");
        //含税金额
        BigDecimal taxamount_purlist =dynamic.getBigDecimal("money");
        //工程施工金额400万及以上触发集团招采字段同步
        boolean case1 = "1104".equals(type) && taxamount_purlist.compareTo(BigDecimal.valueOf(4000000))>=0;
        //其他类型金额200万及以上触发集团招采字段同步
        boolean case2 = !"1104".equals(type) && taxamount_purlist.compareTo(BigDecimal.valueOf(2000000))>=0;
//        if(case1||case2) {
        //if("1104".equals(type)){
          /*  //上传招标（采购）最终文件
            List<Map<String, Object>> sczbcgzzwjs = AttachmentServiceHelper.getAttachments(dynamic.getDynamicObjectType().getName(), dynamic.getPkValue(), "zmee_attachmentpanel1");
            List<Map<String, String>> sczbcgzzwj = OAutil.urlList(sczbcgzzwjs, "sczbcgzzwj");
            if (sczbcgzzwj != null && sczbcgzzwj.size() > 0) {
                for (int i = 0; i < sczbcgzzwj.size(); i++) {
                    mapUrl.add(sczbcgzzwj.get(i));
                }
            }
            //盖章后附件（PDF版本）
            List<Map<String, Object>> gzhfjs = AttachmentServiceHelper.getAttachments(dynamic.getDynamicObjectType().getName(), dynamic.getPkValue(), "zmee_attachmentpanel");
            List<Map<String, String>> gzhfj = OAutil.urlList(gzhfjs, "gzhfj");
            if (gzhfj != null && gzhfj.size() > 0) {
                for (int i = 0; i < gzhfj.size(); i++) {
                    mapUrl.add(gzhfj.get(i));
                }
            }*/
            //招标（采购）设计图纸
            List<Map<String, Object>> attachmentpanel11 = AttachmentServiceHelper.getAttachments(dynamic.getDynamicObjectType().getName(), dynamic.getPkValue(), "zmee_attachmentpanel11");
            List<Map<String, String>> list = OAutil.urlList(attachmentpanel11, "zbcgsjtz");
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    mapUrl.add(list.get(i));
                }
            }
        //}
        log.info("==mainfieldMap==" + mapUrl);
        //招标附件
        List<Map<String, String>> datafieldMap = OAutil.getDatafieldMap(dynamic);
        log.info("==datafieldMap==" + datafieldMap);
        for (Map<String, String> fieldMap : datafieldMap) {
            mapUrl.add(fieldMap);
        }
        //单据数据转请求数据
        FrontWorkflowRequestInfoin0 requestInfoin0 = OARequestUtil.getFrontWorkflowRequestInfoin0(info, mainfieldMap, mapUrl);
        log.info("==requestInfoin0==" + datafieldMap);
        //请求参数
        String body = OARequestUtil.workflowRequestBody(requestInfoin0);
        log.info("==body==" + body);
        //调用OA审批接口
        String request = OARequestUtil.doCreateWorkflowRequest(body);
        String processing = OARequestUtil.requestProcessing(request);
        log.info("==request==" + processing);
        dynamic.set("oaflow",processing);
        SaveServiceHelper.update(dynamic);
    }


    //环能本部请求数据
    private void publishnotice(DynamicObject dynamic, List<Map<String, String>> attacs) {
        //表头请求信息
        Map info = new HashMap();
        info.put("resource", "优采云");
        DynamicObject user = dynamic.getDynamicObject("aosqr");
        info.put("usderid", user.getString("username"));
        info.put("accountType", 1);
        info.put("name", "环能-招标（采购）申请审批流程");//请求标题
        info.put("workflowName", "环能-招标（采购）申请审批流程");//工作流标题
        info.put("workflowId", "38272");//工作流ID
        //info.put("isnextflow", 0);
        //表头字段
        Map<String, Object> mainfieldMap = OAutil.getMainfieldParam(dynamic,user);
        log.info("==mainfieldMap==" + mainfieldMap);
        //分录附件
        List<Map<String, String>> mapUrl = getEntrAttachmentlist(dynamic, "zbcgnr");
        if (attacs != null && attacs.size() > 0) {
            for (int i = 0; i < attacs.size(); i++) {
                mapUrl.add(attacs.get(i));
            }
        }
        log.info("==mainfieldMap==" + mapUrl);
        //单据数据转请求数据
        FrontWorkflowRequestInfoin0 requestInfoin0 = OARequestUtil.getFrontWorkflowRequestInfoin0(info, mainfieldMap, mapUrl);
        log.info("==requestInfoin0==" + requestInfoin0);
        //请求参数
        String body = OARequestUtil.workflowRequestBody(requestInfoin0);
        log.info("==body==" + body);
        //调用OA审批接口
        String request = OARequestUtil.doCreateWorkflowRequest(body);
        String processing = OARequestUtil.requestProcessing(request);
        log.info("==request==" + processing);
        dynamic.set("oaflow",processing);
        SaveServiceHelper.update(dynamic);
    }


    private List<Map<String, String>> getEntrAttachmentlist(DynamicObject dynamic, String txt) {
        List<Map<String, String>> list = new ArrayList<>();
        DynamicObject download = OARequestUtil.getInitialize().config("download");//地址配置
        String downloadURl = download.getString("url");//系统附件存放地址
        String loginToken = BosUtil.getLoginToken();
        DynamicObject biddoc = BusinessDataServiceHelper.loadSingle("src_biddoc_src", "id", new QFilter[]{new QFilter("parentid", QCP.equals, dynamic.getPkValue())});
        DynamicObject biddoc_src = BusinessDataServiceHelper.loadSingle(biddoc.getPkValue(), "src_biddoc_src");
        //分录
        DynamicObjectCollection entitys = biddoc_src.getDynamicObjectCollection("entryentity");
        for (DynamicObject ent : entitys) {
            //附件列表
            DynamicObjectCollection bidattach = ent.getDynamicObjectCollection("bidattach");
            for (int i = 0; i < bidattach.size(); i++) {
                //获取单独字段
                DynamicObject fbase = bidattach.get(i);
                Map<String, String> urls = new HashMap();
                DynamicObject attachment = BusinessDataServiceHelper.loadSingle(fbase.getDynamicObject("fbasedataid").getPkValue(), "bd_attachment");//附件实体
                String url = attachment.getString("url");//附件相对路径
                StringBuilder strurl = new StringBuilder();
                strurl.append(downloadURl);
                strurl.append(url);
                strurl.append("&amp;access_token=");
                strurl.append(loginToken);
                //文件下载地址
                urls.put("fieldName", txt);
                String names = attachment.getString("name");
                String[] split = names.split("&");
                StringBuffer urlname = new StringBuffer();
                for (int j = 0; j < split.length; j++) {
                    if ((j + 1) == split.length) {
                        urlname.append(split[0]);
                    } else {
                        urlname.append(split[0] + "&amp;");
                    }
                }
                urls.put("fieldType", "http:" + urlname);
                urls.put("fieldValue", strurl.toString());//招标文件
                log.info("====resultEnreyUrl====" + urls);
                list.add(urls);
            }
        }
        return list;
    }
}
